package com.socio.resources;

import java.util.Arrays;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.socio.behaviors.DAOBehavior;
import com.socio.behaviors.UserUDIDBehavior;
import com.socio.model.ClientUser;
import com.socio.model.User;
import com.socio.model.responses.SettingsGetResponse;
import com.socio.model.responses.SettingsUpdateResponse;
import com.socio.utils.FieldAccessor.FieldAccessorField;

@Path("/settings")
public class SettingsResource {

	private static final Gson gson = new Gson();
	
	@SuppressWarnings("unchecked")
	@Path("/get")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSettings(@QueryParam("udid") String udid) {
		
		SettingsGetResponse response = new SettingsGetResponse(false);
		if(udid == null)
			return gson.toJson(response);
		DAOBehavior userDAO = new UserUDIDBehavior();
		
		// get user with udid, create user if they aren't already in the db
		User user = null;
		Object result = userDAO.read(udid, null);
        List<Object> userList = (List<Object>)result;
        if(!userList.isEmpty() && userList.get(0) != null) {
        	user = (User)userList.get(0);
        } else {
        	user = new User();
        	user.setAndroidUDID(udid);
        	userDAO.create(user);
        }
        
        response.setSuccess(true);
        response.setUser(user.getClientUser());
        return gson.toJson(response);
	}
	
	@Path("/update")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON)
	public String updateSettings(String json) {
		
		// setup
		SettingsUpdateResponse response = new SettingsUpdateResponse(false);
        ClientUser updatedUser = gson.fromJson(json, ClientUser.class);
		DAOBehavior userDAO = new UserUDIDBehavior();
		
		// update user with nickname
        Object result = userDAO.update(updatedUser.getAndroidUDID(), Arrays.asList(FieldAccessorField.UserNickname),
        		Arrays.asList((Object)updatedUser.getNickname()), null);
        if(result != null)
        	response.setSuccess(true);
        
        return gson.toJson(response);
	}
}
